<template>
  <view class="bill-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">我的账单</view>
    </view>
    
    <!-- 切换标签 -->
    <view class="tab-container">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'month' }" 
        @click="switchTab('month')"
      >
        月账单
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'year' }" 
        @click="switchTab('year')"
      >
        年账单
      </view>
    </view>
    
    <!-- 时间区间选择 -->
    <view class="date-picker-container">
      <uni-datetime-picker
        v-model="dateRange"
        type="daterange"
        rangeSeparator="至"
        @change="dateRangeChange"
        :border="false"
        :clearIcon="true"
        :start="startDate"
        :end="endDate"
        startPlaceholder="开始日期"
        endPlaceholder="结束日期"
      />
    </view>
    
    <!-- 总计区域 -->
    <!-- <view class="summary-area">
      <view class="summary-item">
        <text class="summary-label">收入</text>
        <text class="summary-value income">¥{{ totalIncome }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">和款</text>
        <text class="summary-value expense">¥{{ totalExpense }}</text>
      </view>
    </view> -->
    
    <!-- 月度账单列表 -->
    <scroll-view scroll-y class="bill-list" v-if="activeTab === 'month'">
      <view class="month-item" v-for="(month, index) in monthlyBills" :key="index">
        <view class="month-header">
          <text class="month-title">{{ month.month }}月</text>
        </view>
        <view class="month-details">
          <view class="detail-row">
            <view class="detail-label">收入</view>
            <view class="detail-value income">¥{{ month.income }}</view>
          </view>
          <view class="detail-row">
            <view class="detail-label">扣款</view>
            <view class="detail-value expense">¥{{ month.expense }}</view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 年度账单列表 -->
    <scroll-view scroll-y class="bill-list" v-if="activeTab === 'year'">
      <view class="year-item" v-for="(year, index) in yearlyBills" :key="index">
        <view class="year-header">
          <text class="year-title">{{ year.year }}年</text>
        </view>
        <view class="year-details">
          <view class="detail-row">
            <view class="detail-label">收入</view>
            <view class="detail-value income">¥{{ year.income }}</view>
          </view>
          <view class="detail-row">
            <view class="detail-label">扣款</view>
            <view class="detail-value expense">¥{{ year.expense }}</view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getBillData, getMonthlyBill, getYearlyBill } from '@/api/app/master/transactionlog.js'

export default {
  data() {
    const currentDate = new Date()
    const currentYear = currentDate.getFullYear()
    const currentMonth = currentDate.getMonth() + 1
    
    // 计算默认的日期范围：当前月的第一天到最后一天
    const firstDay = new Date(currentYear, currentMonth - 1, 1)
    const lastDay = new Date(currentYear, currentMonth, 0)
    
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    // 设置可选日期范围
    const startDate = '2020-01-01'
    const endDate = formatDate(new Date())
    
    return {
      activeTab: 'month', // 默认显示月账单
      dateRange: [formatDate(firstDay), formatDate(lastDay)], // 默认选择当前月
      startDate: startDate, // 可选日期范围开始
      endDate: endDate, // 可选日期范围结束
      totalIncome: '11,235.6',
      totalExpense: '1000',
      monthlyBills: [
        { month: 5, income: '1354.5', expense: '10' },
        { month: 4, income: '1354.5', expense: '0' },
        { month: 3, income: '1354.5', expense: '5' },
        { month: 2, income: '1354.5', expense: '0' }
      ],
      yearlyBills: [
        { year: 2024, income: '11,235.6', expense: '1000' },
        { year: 2023, income: '8,456.2', expense: '500' }
      ],
      billData: null,
      loading: false
    }
  },
  onLoad() {
    // 页面加载时获取账单数据
    this.loadBillData()
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    switchTab(tab) {
      this.activeTab = tab
      // 切换标签时加载对应数据
      if (tab === 'month') {
        this.loadMonthlyBillData()
      } else {
        this.loadYearlyBillData()
      }
    },
    // 日期区间选择变更
    dateRangeChange(dateRange) {
      if (!dateRange || !dateRange.length) return
      
      console.log('选择的日期区间:', dateRange)
      
      // 根据当前标签加载对应数据
      if (this.activeTab === 'month') {
        this.loadMonthlyBillData()
      } else {
        this.loadYearlyBillData()
      }
    },
    
    // 加载账单总数据
    loadBillData() {
      if (!this.dateRange || !this.dateRange.length) return
      
      this.loading = true
      
      getBillData({
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      }).then(res => {

        console.log('获取账单总数据成功', res)

        if (res.code == 200 && res.data) {
          // 更新总收入和支出
          if (res.data.totalIncome) {
            this.totalIncome = this.formatMoney(res.data.totalIncome)
          }
          
          if (res.data.totalExpense) {
            this.totalExpense = this.formatMoney(res.data.totalExpense)
          }
          
          // 根据当前标签加载详细数据
          if (this.activeTab === 'month') {
            this.loadMonthlyBillData()
          } else {
            this.loadYearlyBillData()
          }
        }
      }).catch(err => {

        console.error('获取账单总数据失败', err)
        uni.showToast({
          title: '获取账单数据失败',
          icon: 'none'
        })

      }).finally(() => {
        this.loading = false
      })
    },
    
    // 加载月度账单数据
    loadMonthlyBillData() {
      if (!this.dateRange || !this.dateRange.length) return
      
      this.loading = true
      
      getMonthlyBill({
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      }).then(res => {
        if (res.code === 200 && res.data && Array.isArray(res.data)) {
          this.monthlyBills = res.data.map(item => ({
            month: item.month,
            income: this.formatMoney(item.income || 0),
            expense: this.formatMoney(item.expense || 0)
          }))
        }
      }).catch(err => {
        console.error('获取月度账单数据失败', err)
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 加载年度账单数据
    loadYearlyBillData() {
      if (!this.dateRange || !this.dateRange.length) return
      
      this.loading = true
      
      getYearlyBill({
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      }).then(res => {
        if (res.code === 200 && res.data && Array.isArray(res.data)) {
          this.yearlyBills = res.data.map(item => ({
            year: item.year,
            income: this.formatMoney(item.income || 0),
            expense: this.formatMoney(item.expense || 0)
          }))
        }
      }).catch(err => {
        console.error('获取年度账单数据失败', err)
      }).finally(() => {
        this.loading = false
      })
    },
    // 格式化金额
    formatMoney(amount) {
      if (typeof amount === 'number') {
        return amount.toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
      }
      return amount
    }
  }
}
</script>

<style lang="scss" scoped>
.bill-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #0088ff;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
}

/* 切换标签 */
.tab-container {
  display: flex;
  background-color: #0088ff;
  padding: 0 60rpx 20rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  color: rgba(255, 255, 255, 0.7);
  font-size: 32rpx;
  padding: 10rpx 0;
  position: relative;
}

.tab-item.active {
  color: #ffffff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -10rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background-color: #ffffff;
  border-radius: 3rpx;
}

/* 日期选择区域 */
.date-picker-container {
  background-color: #f5f5f5;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
}

/* 总计区域 */
.summary-area {
  display: flex;
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  border-bottom: 1rpx solid #eee;
}

.summary-item {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.summary-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.summary-value {
  font-size: 32rpx;
  font-weight: bold;
}

.income {
  color: #333;
}

.expense {
  color: #ff4d4f;
}

/* 账单列表 */
.bill-list {
  background-color: #fff;
  height: calc(100vh - 300rpx);
}

/* 月度账单项 */
.month-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.month-header {
  margin-bottom: 20rpx;
}

.month-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.month-details, .year-details {
  display: flex;
  flex-direction: column;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.detail-label {
  font-size: 28rpx;
  color: #999;
}

.detail-value {
  font-size: 28rpx;
}

/* 年度账单项 */
.year-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.year-header {
  margin-bottom: 20rpx;
}

.year-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
</style>